<?php

namespace app\admin\controller\meeting;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 会议信息
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * Index模型对象
     * @var \app\admin\model\meeting\Index
     */
    protected $model = null;

    private  $appid='wxc6d6c0436e704251';
    private $secret='a9a075175dd0821dfe96212600cf3507';



    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\meeting\Index;

    }



    /**

     */
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as $k=>$v){
             $v->all= getalluser($v->team_id);
             $v->in = getallgin($v->id);
            if (!empty($v->team_id) && is_string($v->team_id)) {
                $teamIds = explode(',', $v->team_id);
                $teamNames = [];
                foreach ($teamIds as $teamId) {
                    $team = Db::name('team')->where('id', $teamId)->find();
                    if ($team) {
                        $teamNames[] = $team['name'];
                    }
                }
                $v->team_name = implode(',', $teamNames);
            }

        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {


        $SexList=Db::name('team')->select();

        $this->assign('SexList',$SexList);



        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');


        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (isset($params['team_id']) && is_array($params['team_id'])) {
            $params['team_id'] = implode(',', $params['team_id']);
        }


        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {



        $SexList=Db::name('team')->select();

        $this->assign('SexList',$SexList);


        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if (isset($params['team_id']) && is_array($params['team_id'])) {
            $params['team_id'] = implode(',', $params['team_id']);
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    // 参会
    public function detail($ids = null){


        $this->view->assign('id', $ids);
        return $this->view->fetch();


    }

    public function getlist($ids = null)
    {


        $meeting = Db::name('meeting')->where('id', $ids)->find();

        // 优化：使用JOIN一次性获取用户及签到信息，避免循环查询
        $lists = Db::name('user')->alias('u')
            ->field('u.*, IF(ms.id IS NULL, 0, 1) as is_sign, ms.addtime as sign_addtime')
            ->where('u.team_id', 'in',$meeting['team_id'])
            ->join('meeting_sign ms', 'ms.user_id = u.id AND ms.meeting_id = ' . $ids, 'LEFT')
            ->select();

        foreach ($lists as &$list){
            $list['is_signt'] = $list['is_sign'] ? '已签到' : '未签到';

            $list['addtime']=date('Y-m-d H:i',$list['sign_addtime']);
        }


        return json($lists);

    }
    //签到
    public function setsing(){

        $uid=$this->request->param('ids');
        $id=$this->request->param('metid');


        $qiandao=Db::name('meeting_sign')
            ->where('meeting_id',$id)
            ->where('user_id',$uid)
            ->find();

        if ($qiandao){
            $this->error('已签到');
        }


        Db::name('meeting_sign')
            ->data(['meeting_id'=>$id,'user_id'=>$uid,'addtime'=>time()])
            ->insert();

        $this->success('签到成功');



    }


    /**
     * 获取小程序太阳吗
     */
    public function getqrcode($ids = null){

        $id=$this->request->param('ids');

        $meet=Db::name('meeting')->where('id',$id)
            ->find();

        $imgfile="./uploads/qrcode/".md5($id).".png";

        if (file_exists($imgfile)){


            return $this->outputFile($imgfile,$meet['name']);
//            $this->success('','http://'.$_SERVER['HTTP_HOST'].substr($imgfile,1));
        }

        $appid=$this->appid;
        $appsecret=$this->secret;

        $access_token = $this->getaccess_token($appid, $appsecret);


        $access_token = $access_token['access_token'];

        $request_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $request_data = array(
            'scene' =>$id,
            'page' => 'pages/qiandao/index',
            'width' => '690',
            'is_hyaline'=>true
        );

        $img =$this->https_request($request_url, $request_data, 'json');


        $imgfile="/uploads/".md5($id).".png";

        $filename =  ".".$imgfile;//要生成的图片名字


        $file = fopen($filename, "w");//打开文件准备写入

        fwrite($file, $img);//写入

        fclose($file);//关闭

        return $this->outputFile($filename,$meet['name']);

//        $this->success('图片',cdnurl($imgfile,true));

    }




    public function getaccess_token($appid, $appsecret)  {

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, 0);
        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);


        // close curl resource to free up system resources
    }

    public function https_request($url = '', $param = [], $contentType = ''){
        $ch = curl_init();

        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);

        // 请求参数类型
        $param = $contentType == 'json' ? json_encode($param) : $param;

        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // post提交
        if ($param) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }

        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 执行并接收响应结果
        $output = curl_exec($ch);

        // 关闭curl
        curl_close($ch);

        return $output !== false ? $output : false;
    }

    public function outputFile($filePath,$fileName)
    {
        // 检查文件是否存在
        if (!file_exists($filePath)) {
            return $this->error('文件不存在');
        }

        // 如果没有提供文件名，则使用原文件名

        $fileName=$fileName.'.png';
        if (empty($fileName)) {
            $fileName = basename($filePath);
        }

        // 设置响应头
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Content-Length: ' . filesize($filePath));

        // 清除缓冲区
        ob_clean();
        flush();

        // 输出文件内容
        readfile($filePath);
        exit;
    }



}
